package com.android.duininsuoai.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.duininsuoai.adapt.MainlistAdapt;
import com.android.duininsuoai.app.BaseActivity;
import com.android.duininsuoai.model.group.MainList;
import com.android.duininsuoai.model.group.MainListCallback;
import com.android.duininsuoai.model.group.SortHeadThumbData;
import com.android.duininsuoai.utils.ConstantsUrl;
import com.android.duininsuoai.utils.HttpUtils;
import com.android.duininsuoai.utils.MyLog;
import com.android.duininsuoai.utils.ObjectUtils;
import com.android.duininsuoai.R;
import com.android.duininsuoai.model.group.SortHeadThumbDataCallback;
import com.android.duininsuoai.view.recycleview.CustomLoadMoreView;
import com.android.duininsuoai.view.recycleview.CustomRecycleView;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class MainRecommendType extends BaseActivity implements BaseQuickAdapter.RequestLoadMoreListener {

    @BindView(R.id.listView)
    CustomRecycleView mRecyclerView;
    @BindView(R.id.swipe_refresh_layout)
    SwipeRefreshLayout mRefreshLayout;
    @BindView(R.id.progress)
    RelativeLayout progress;
    @BindView(R.id.no_data_tv)
    TextView noDataTv;
    @BindView(R.id.no_data)
    RelativeLayout noData;
    @BindView(R.id.click_resetnetwork_msg)
    TextView clickResetnetworkMsg;
    @BindView(R.id.click_resetnetwork_refresh)
    TextView clickResetnetworkRefresh;
    @BindView(R.id.click_resetnetwork)
    LinearLayout clickResetnetwork;
    private boolean networkConnected;
    private MainlistAdapt adapter;
    private int page = 1;
    private MainRecommendType mcontext;
    private String type;
    private String sorttitle;
    private LinearLayoutManager mLayoutManager;
    private GridLayoutManager mGridLayoutManager;
    private View head;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_recycle_refresh);
        ButterKnife.bind(this);
        mcontext = MainRecommendType.this;
        sorttitle = getIntent().getStringExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_SORT_SHOW_TITLE);
        type = getIntent().getStringExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_SORT_SHOW_LINK);
        initTitle(0, sorttitle);
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        initUI();
        if (networkConnected) {
            GetTypeData(true);
        } else {

            ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
        }


    }

    private void initRecycle() {
        adapter = new MainlistAdapt(mcontext, null, type);
        adapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        adapter.setLoadMoreView(new CustomLoadMoreView());
        adapter.setOnLoadMoreListener(this, mRecyclerView);
        mLayoutManager = new LinearLayoutManager(mcontext);
        mGridLayoutManager = new GridLayoutManager(mcontext, 2);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(adapter);
        mRecyclerView.GetToTop((ImageView) findViewById(R.id.top), 0);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter1, View view, int position) {
                switch (type) {
                    case "3":
                    case "6":
                        Intent intent = new Intent(mcontext, GoodsDetailActivity.class);
                        int end = Integer.parseInt(adapter.getItem(position).getEnd_time());
                        int start = Integer.parseInt(adapter.getItem(position).getStart_time());
                        int run = adapter.getItem(position).getRun_time();
                        if (run > end && run > start) {
                            intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_DETAIL_SHOW, 5);
                        } else if (run > start && run < end) {
                            intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_DETAIL_SHOW, 1);
                        } else if (run < start) {
                            intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_DETAIL_SHOW, 3);
                        }

                        intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_DETAIL_ID, adapter.getItem(position).getId());
                        startActivity(intent);
                        break;
                    default:
                        ObjectUtils.ToDetailActivity(mcontext, 1, adapter.getItem(position).getId(), "");
                        break;
                }

            }
        });
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public boolean onItemChildClick(BaseQuickAdapter adapter1, View view, int position) {
                switch (view.getId()) {
                    case R.id.main_list_item_go_kai:
                    case R.id.ll_free:
                        ObjectUtils.ToDetailActivity(mcontext, 1, adapter.getItem(position).getId(), "");
                        break;
                    case R.id.ll_start_soon:
                        ObjectUtils.ToDetailActivity(mcontext, 3, adapter.getItem(position).getId(), "");
                        break;
                    case R.id.ll_result:
                        Intent intent = new Intent(mcontext, BaseObject.class);
                        intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE, "试用结果");
                        intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_NEED_ID, adapter.getItem(position).getId());
                        startActivity(intent);
                        break;

                }
                return false;
            }
        });
    }

    private void initUI() {
        head = getLayoutInflater().inflate(R.layout.item_list_sort_dapai, null, false);
        head.findViewById(R.id.ll_msg).setVisibility(View.GONE);
        initRecycle();
        switch (type) {
            case "3":
            case "6":
                adapter.addHeaderView(head);
                break;
            default:
                break;
        }

        Refresh();
    }


    private void Refresh() {
        mRefreshLayout.setColorSchemeResources(R.color.app_title);
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                networkConnected = ObjectUtils.isNetworkConnected(mcontext);
                if (networkConnected) {
                    page = 1;
                    GetTypeData(true);
                } else {
                    ObjectUtils.toast(mcontext, "网络连接出现异常");
                    mRefreshLayout.setRefreshing(false);
                }
            }
        });

    }

    @OnClick(R.id.click_resetnetwork_refresh)
    public void onClick() {
        ObjectUtils.GetDataNet(clickResetnetwork, progress, 3);
        page = 1;
        GetTypeData(true);
    }

    @Override
    public void onLoadMoreRequested() {
        page = page + 1;
        GetTypeData(false);
    }

    private void GetTypeData(boolean isloadhead) {
        switch (type) {
            case "3":
                if (isloadhead) {

                    GetDataHeadImage("goods/ad/5");
                }
                GetListData(page, "&typeid=5&order=lottery");
                break;
            case "4":
                GetListData(page, "&typeid=2");
                break;

            case "6":
                if (isloadhead) {

                    GetDataHeadImage("goods/ad/6");
                }
                GetListData(page, "&typeid=6&order=lottery");
                break;
            case "7":
                GetListData(page, "&typeid=7");
                break;
            case "8":
                //推广
                GetListData(page, "&typeid=8");
                break;
            case "9":
                //自选
                GetListData(page, "&typeid=9");
                break;
            case "10":
                //阶梯
                GetListData(page, "&typeid=10");
                break;
        }

    }


    //获取主页列表数据
    private void GetListData(final int page, String linktype) {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        String address = ConstantsUrl.domain + ConstantsUrl.MAIN_LISTDATA + "?page=" + page + linktype;
        MyLog.e("地址", address);
        if (networkConnected) {
            HttpUtils.get(address, null, new MainListCallback() {

                @Override
                public void onError(Call call, Exception e, int id) {
                    mRefreshLayout.setRefreshing(false);
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
                }

                @Override
                public void onResponse(MainList response, int id) {
                    mRefreshLayout.setRefreshing(false);
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);

                    if (response.getCode() == 0) {

                        List<MainList.MainListdata.Mainlistdata> list = response.getData().getList();
                        if (list == null && page == 1) {
                            noData.setVisibility(View.VISIBLE);
                            return;
                        }
                        ArrayList<MainList.MainListdata.Mainlistdata> listdata = new ArrayList<>();

                        if (list != null && list.size() > 0) {

                            if (type.equals("3") || type.equals("6")) {
                                for (int i = 0; i < list.size(); i++) {
                                    listdata.add(new MainList.MainListdata.Mainlistdata(0, list.get(i).getId()
                                            , list.get(i).getTypeid(), list.get(i).getName(), list.get(i).getPrice(), list.get(i).getTeam_price(), list.get(i).getDiscount_price()
                                            , list.get(i).getThumb(), list.get(i).getTeam_num(), list.get(i).getTeam_people_num(), list.get(i).getLuck_num(), list.get(i).getEnd_time()
                                            , list.get(i).getStart_time(), list.get(i).getRun_time()));
                                }
                                mRecyclerView.setLayoutManager(mLayoutManager);
                                mRecyclerView.setAdapter(adapter);
                                if (page == 1) {
                                    adapter.setNewData(listdata);
                                } else {
                                    adapter.addData(listdata);
                                    adapter.loadMoreComplete();
                                }
                            } else {
                                for (int i = 0; i < list.size(); i++) {
                                    listdata.add(new MainList.MainListdata.Mainlistdata(response.getData().getList_type(), list.get(i).getId()
                                            , list.get(i).getTypeid(), list.get(i).getName(), list.get(i).getPrice(), list.get(i).getTeam_price(), list.get(i).getDiscount_price()
                                            , list.get(i).getThumb(), list.get(i).getTeam_num(), list.get(i).getTeam_people_num(), list.get(i).getLuck_num(), list.get(i).getEnd_time()
                                            , list.get(i).getStart_time(), list.get(i).getRun_time()));
                                }
                                if (page == 1) {
                                    adapter.setNewData(listdata);

                                    if (response.getData().getList_type() == 0) {
                                        mRecyclerView.setLayoutManager(mLayoutManager);
                                        mRecyclerView.setAdapter(adapter);
                                    } else {
                                        mRecyclerView.setLayoutManager(mGridLayoutManager);
                                        mRecyclerView.setAdapter(adapter);
                                    }

                                } else {
                                    adapter.addData(listdata);
                                    adapter.loadMoreComplete();
                                }
                            }
                        } else {
                            adapter.loadMoreEnd();
                        }
                    } else {
                        noData.setVisibility(View.VISIBLE);
                        noDataTv.setVisibility(View.VISIBLE);
                        noDataTv.setText(response.getMsg());
                    }
                }
            });
        } else {
            if (page == 1) {
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
            }
            ObjectUtils.toast(mcontext, "网络连接出现异常");
            adapter.loadMoreFail();
        }
    }

    private void GetDataHeadImage(String imagetype) {
        String address = ConstantsUrl.domain + imagetype;
        HttpUtils.get(address, null, new SortHeadThumbDataCallback() {

            @Override
            public void onError(Call call, Exception e, int id) {
            }

            @Override
            public void onResponse(SortHeadThumbData response, int id) {
                if (response.getData() != null) {

                    ObjectUtils.photo2(mcontext, response.getData(), (ImageView) head.findViewById(R.id.item_list_sort_dapai_img));
                    adapter.notifyDataSetChanged();
                }

            }

        });

    }


}
